<!--  -->
<template>
  <div class="box">
    <!-- search组件 -->
    <search :state="State" @onSubmit="onSubmit" />
    <!-- table表单 -->
    <div class="result">
      <el-row style="height:60px">
        <btn :dialog="dialogVisible" :title="title" @showDialog="showDialog" @close="dialogClose" @create="createFn">
          <template #btn>
            <el-button type="primary" @click="gdFn">工单配置</el-button>
          </template>
          <template #main>
            <!--
              model 表单数据
              rules	表单验证规则
              ref validate
              prop	表单域 model 字段，在使用 validate、resetFields 方法的情况下，该属性是必填的
              rules	表单验证规则
             -->
            <!-- 新增表单 -->
            <el-form ref="ruleForm" :rules="rules" :model="ruleForm" label-width="100px">
              <el-form-item label="设备编号:" prop="innerCode" style="width:520px">
                <el-input
                  v-model="ruleForm.innerCode"
                  placeholder="请输入"
                  maxlength="15"
                  show-word-limit
                  debounce
                  @input="Changecode"
                />
              </el-form-item>
              <el-form-item label="工单类型:" prop="productType">
                <el-select v-model="ruleForm.productType" value-key="productType" placeholder="请选择" style="width:420px">
                  <el-option label="补货工单" value="补货工单" />
                </el-select>
              </el-form-item>
              <el-form-item ref="TaskRef" label="补货数量:" prop="details" style="width:520px">
                <el-button type="text" class="iconfont icon-dingdan bh" @click="openTask"> 补货清单</el-button>
              </el-form-item>
              <el-form-item label="运营人员:" prop="Operators">
                <el-select v-model="ruleForm.userId" placeholder="请选择" style="width:420px">
                  <el-option v-for="item in ruleForm.Operators" :key="item.userId" :label="item.userName" :value="item.userId" />
                </el-select>
              </el-form-item>
              <el-form-item label="备注" prop="desc">
                <el-input v-model="ruleForm.desc" placeholder="请输入备注(不超过40字)" maxlength="40" show-word-limit type="textarea" style="width:420px" />
              </el-form-item>
            </el-form>
            <!-- 新增表单end -->
          </template>
        </btn>
      </el-row>
      <el-table
        :data="list"
        highlight-current-row
        :header-cell-style="{ background:'rgb(243, 246, 251)', color: 'rgb(102, 102, 102)','font-weight':'500',width:'0'}"
      >
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="120"
        />
        <el-table-column
          prop="taskCode"
          label="工单编号"
          width="180"
        />
        <el-table-column
          prop="innerCode"
          label="设备编号"
        />
        <el-table-column
          prop="taskType.typeName"
          label="工单类型"
        />
        <el-table-column
          label="工单方式"
        >
          <template #default="scope">
            {{ createType[+scope.row.createType] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="taskStatus"
          label="工单状态"
        >
          <template #default="scope">
            {{ taskStatus[+scope.row.taskStatus] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="userName"
          label="运营人员"
        />
        <el-table-column
          prop="createTime"
          label="创建日期"
        >
          <template #default="scope">
            {{ createTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" class="cz" @click="ckxq(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <TablePaging :params="params" @handleSizeChange="handleSizeChange" @currentPageChange="currentPageChange" />
      <!--补货弹框 -->
      <el-dialog
        :title="title1"
        :visible="dialogVisibleT"
        @close="cloceTask"
      >
        <el-table
          height="320"
          :data="detailsArr"
          highlight-current-row
          :header-cell-style="{ background:'rgb(243, 246, 251)', color: 'rgb(102, 102, 102)','font-weight':'500'}"
        >
          <el-table-column
            label="货道编号"
            prop="channelCode"
            width="92"
          />
          <el-table-column
            label="商品名称"
            width="92"
          >
            <template #default="scope">
              {{ scope.row.sku?scope.row.sku.skuName:'-' }}
            </template>
          </el-table-column>
          <el-table-column
            label="当前数量"
            width="92"
          >
            <template #default="scope">
              {{ scope.row.sku? scope.row.currentCapacity:'-' }}
            </template>
          </el-table-column>
          <el-table-column
            label="还可添加"
            width="92"
          >
            <template #default="scope">
              {{ scope.row.sku? (scope.row.num-scope.row.maxCapacity):'-' }}
            </template>
          </el-table-column>
          <!-- 计数器 -->
          <el-table-column
            label="补满数量"
            width="200"
          >
            <template #default="scope">
              <el-input-number v-if="scope.row.sku" v-model="scope.row.maxCapacity" prop="num" controls-position="right" :min="0" :max="scope.row.max" @change="handleChange(scope.row,scope.$index)" />
              <div v-else>-</div>
            </template>
          </el-table-column>
          <!-- 计数器end -->
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button class="btn2" @click="cloceTask">取 消</el-button>
          <el-button type="primary" class="btn" @click="cloceTask">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <GDPZ :dialog="GDPZ" :title="title2" @close="Gdpz" @btn="sbumitConifg">
      <template #main>
        <div style="margin-left:50px">
          补货警戒线:
          <el-input-number v-model="Yjz" style="width:400px" label="123" controls-position="right" :min="1" :max="100" />
        </div>

      </template>
    </GDPZ>
    <!-- 查看详情弹框 -->
    <Ckxq :dialog="CKXQ" :status="CKXQarr" @close="Ckxq" @create="create" @del="del" />
  </div>
</template>
<script>
import search from './search.vue'
import btn from '@/components/Dialog/btn'
import TablePaging from '@/components/TablePaging'
import GDPZ from './dialog/Gdpz.vue'
import Ckxq from './dialog/Ckxq.vue'
import dayjs from 'dayjs'
import { del, getTaskInfo, getautoSupplyConfige, getsupplyAlertValue, getWork, getState, getTaskType, getChannel, getOperatorList, getCreate } from '@/api'
export default {
  components: {
    TablePaging,
    search,
    btn,
    GDPZ,
    Ckxq
  },
  data() {
    return {
      arr: [],
      Yjz: 0,
      GDPZ: false,
      CKXQ: false,
      CKXQarr: {},
      rules: {
        innerCode: [
          { required: true, message: '请输入', trigger: 'change' }
        ],
        productType: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        Operators: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        desc: [
          { required: true, message: '请输入', trigger: 'change' }
        ]
      },
      ruleForm: {
        // 设备编号
        innerCode: '01000062',
        // 工单类型
        productType: '',
        // 运营人员
        Operators: '',
        // 备注
        desc: '',
        userId: ''
      },
      details: [{
        channelCode: '1-2',
        expectCapacity: 10,
        skuId: '2',
        skuName: '康师傅冰红茶',
        skuImage: ''
      }],
      // 补货数组
      detailsArr: [],
      value: '',
      // 标题
      title: '新增工单',
      title1: '补货详情',
      title2: '工单配置',

      dialogVisible: false,
      dialogVisibleT: false,
      // 待办
      State: [],
      // 工单类型
      TaskType: [],

      // 工单搜索列表
      list: [],

      // 分页器初始数据
      params: {
        /*
        第几页
        每页个数
        总数居条数
        总页数
        */
        pageIndex: 1,
        pageSize: 10,
        totalCount: 0,
        totalPage: 0
      },
      // 子传父数据
      search: {
        pageIndex: 1,
        pageSize: 10,
        isRepair: false
      },
      // 自动手动枚举
      createType: {
        0: '自动',
        1: '手动'
      },
      taskStatus: {
        1: '待办中',
        2: '进行中',
        3: '已取消',
        4: '已完成'
      }
    }
  },
  async created() {
    // 调用获取列表
    this.fetchWork()
    const res = await getTaskType()
    this.TaskType = res.data
  },
  methods: {
    async gdFn() {
      this.GDPZ = true
      const res = await getsupplyAlertValue()
      this.Yjz = res.data
    },
    async sbumitConifg() {
      await getautoSupplyConfige({ alertValue: this.Yjz })
      this.GDPZ = false
    },
    // 按钮
    handleChange(value, index) {
      this.details[index].expectCapacity = value.maxCapacity
    },

    // 搜索
    async onSubmit(val) {
      this.search = val
      await this.fetchWork()
    },
    // 获取列表
    async fetchWork() {
      const res = await getWork(this.search)
      this.list = res.data.currentPageRecords
      this.params = res.data
      // 待办
      const res1 = await getState()
      this.State = res1.data
    },
    // 子组件传入每页显示数
    handleSizeChange(newPage) {
      this.search.pageSize = newPage
      this.fetchWork()
    },
    // 页码发生变化传入当前页调用
    currentPageChange(newPage) {
      // this.params.pageIndex = newPage
      this.search.pageIndex = newPage
      this.fetchWork()
    },
    // 打开弹窗
    showDialog() {
      this.dialogVisible = true
    },
    // 关闭弹窗
    dialogClose() {
      this.dialogVisible = false
      this.$refs['ruleForm'].resetFields()
      this.ruleForm = {
        innerCode: '01000062',
        productType: '',
        details: {},
        Operators: '',
        desc: '',
        userId: ''
      }
    },
    createFn() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (!valid) return
        try {
          const res = await getCreate({
            userId: 1,
            createType: 1,
            innerCode: this.ruleForm.innerCode,
            assignorId: this.ruleForm.userId,
            productType: 2,
            desc: this.ruleForm.desc,
            details: this.details
          })
          this.dialogVisible = false
          this.fetchWork()
          console.log(res)
        } catch (err) {
          console.log(err.message)
        }
      })
    },
    async Changecode() {
      if (!this.ruleForm.innerCode.length) return
      const res = await getOperatorList(this.ruleForm.innerCode)

      this.ruleForm.Operators = res.data
    },
    // 时间转换
    createTime(val) {
      return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
    },
    // 打开捕获
    openTask() {
      this.$refs.ruleForm.validateField('innerCode', async(errorMessage) => {
        if (errorMessage) return
        this.dialogVisibleT = true
        const { data } = await getChannel(this.ruleForm.innerCode)
        console.log(data)
        const arr = data.map(item => {
          if (item.sku) {
            return Object.assign({}, { channelCode: item.channelCode, expectCapacity: item.maxCapacity, skuId: item.skuId, skuName: item.sku.skuName, skuImage: item.sku.skuImage })
          }
        })
        const arr1 = arr.filter(res => res !== undefined)
        this.details = arr1
        data.forEach(item => {
          item.num = item.maxCapacity
          item.max = item.maxCapacity
        })
        this.detailsArr = data
      })
    },
    // 关闭弹窗
    cloceTask() {
      this.dialogVisibleT = false
    },
    Gdpz() {
      this.GDPZ = false
    },
    Ckxq() {
      this.CKXQ = false
    },
    async create(id) {
      // 运营人员
      const { data } = await getOperatorList(id)
      // 查看详情
      const res = await getTaskInfo(this.CKXQarr.taskId)
      console.log(res.data)
      this.dialogVisible = true
      this.CKXQ = false
      this.ruleForm = {
        innerCode: id,
        productType: res.data.taskType.typeName,
        details: {},
        Operators: data,
        desc: res.data.desc,
        userId: res.data.userName
      }
    },
    async del() {
      this.$confirm('取消工单后，将不能恢复，是否确认取消？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const num = this.CKXQarr.taskId + ''
        const res = await del({
          taskId: num,
          desc: '123'

        })
        console.log(res)
        this.$message.success('删除员工成功')
        // 带有分页的页面删除时需要考虑边界情况
        if (this.list.length === 1 && this.params.page > 1) {
          this.params.page--
        }
        this.fetchWork()
      })
    },
    async ckxq(val) {
      this.CKXQ = true
      const { data } = await getTaskInfo(val.taskId)
      this.CKXQarr = data
      console.log(this.CKXQarr)

      this.CKXQarr.createTime = this.CKXQarr.createTime.replace(/T/, '  ')
      this.CKXQarr.updateTime = this.CKXQarr.updateTime.replace(/T/, '  ')
    }
  }
}
</script>
<style lang='scss' scoped>
.result {
  background-color: #fff;
  height: 801px;
.bh{
  font-size: 14px;
}
  .el-row {
    display: flex;
    align-items: center;
    padding-left: 17px;
    padding-top: 12px;
    .el-button:nth-child(2) {
      margin-left: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 80px !important;
      height: 36px;
      padding: 0;
      background-color: #fbf4f0;
      border: none;
      color: #655b56 !important;
    }
    .el-button:nth-child(2):hover {
      background-color: #f3e7e1;
    }
  }
  .el-table {
    padding: 10px 17px;
  }
  .cz {
    border-color: transparent;
    color: #5f84ff;
    background: transparent;
    padding-left: 0;
    padding-right: 0;
  }
  .block{
    width: 100%;
  }
}
::v-deep .el-table td, .el-table th.is-leaf{
  padding: 6px 0;
  border: 0;
}
::v-deep .el-dialog__title{
  color: #333 ;
  font-size: 16px;
  font-weight: 600;
}
 ::v-deep .el-dialog,::v-deep .el-dialog__header{
  background: #fff !important;
  border-radius: 10px !important;
  width: 630px !important;
}
::v-deep .el-dialog__header .el-icon-close:before{
  color: #333;
}

::v-deep .el-dialog__footer{
  text-align: center;
}
  .btn2{
      justify-content: center;
      align-items: center;
      width: 80px !important;
      height: 36px;
      padding: 0;
      background-color: #fbf4f0;
      border: none;
      color: #655b56 !important;
      margin-right: 34px;
    }
    .btn2:hover {
      background-color: #f3e7e1;
    }
  .btn {
    align-items: center;
    width: 80px!important;
    height: 36px;
    padding: 0;
    background: linear-gradient(135deg,#ff9743,#ff5e20);
    border: none;
    }
    .btn:hover {
      width: 200px;
      background: linear-gradient(135deg, #ff9743, #e20);
    }

::v-deep .el-dialog__body{
  padding: 30px 5px;

}
</style>
